<template>
  <el-dialog :visible="openModal" width="60%" :close-on-click-modal="false" @opened="initTable">
    <el-form ref="formData" :model="formData">
      <el-row>
        <el-col :span="8">
          <el-form-item prop="title" label="重量段方案名称">
            <el-input v-model="formData.title" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="8">
          <el-form-item prop="" label="快速粘贴区">
            <el-input v-model="formData.weightTxt" :rows="14" type="textarea" clearable placeholder="请输入内容" />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="margin-left: 80px;" @click="previewClick()"> 预览</el-button>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <div ref="hotTable" class="hotTable" style="width: 100%" />
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer">
      <el-button type="primary" @click="openModal=false">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import 'handsontable/dist/handsontable.full.css'
import Handsontable from 'handsontable'
import request from '@/utils/request'
import { copyProperty } from '@/utils/tools'
export default {
  data() {
    return {
      openModal: false,
      formData: {
        id: '',
        weightTxt: '',
        title: '',
        specs: []
      },
      hotTableObj: null,
      newWeights: [], // 表格数字
      newWeightsOld: [],
      newWeightsArr: [], // 用于生成3 4 列数据
      newWeightsObj: {}, // 对象数组
      newWeightsCopy: [],
      hotSettings: {
        data: [],
        minSpareRows: 1,
        rowHeaders: true,
        width: '100%',
        height: '500px',
        autoColumnSize: true,
        manualColumnResize: true,
        colHeaders: [
          '重量段标题<span style="color:red;">*</span>',
          '计费种类(固定费用,续费重,单价)<span style="color:red;">*</span>',
          '开始重量<span style="color:red;">*</span>',
          '结束重量<span style="color:red;">*</span>',
          '计费单重<span style="color:red;">*</span>'
        ],
        columns: [
          {
            data: 'title' // 重量段标题
          },
          {
            data: 'chargeType' // 计费种类
          },
          {
            data: 'fromWeight' // 开始重量
          },
          {
            data: 'toWeight' // 结束重量
          },
          {
            data: 'unitWeight' // 计费单重
          }
        ],
        licenseKey: 'non-commercial-and-evaluation'
      },
      doEdit: false
    }
  },

  watch: {
    'formData.weightTxt': {
      handler(newValue, oldValue) {
        const weights = newValue.split(/\n|\s+/).toString()
        this.newWeights = weights.match(/\d+(\.\d+)?/g)
        this.newWeightsCopy = weights.match(/\d+(\.\d+)?/g)
      },
      deep: true,
      immediate: true
    }
  },
  mounted() {
  },
  created() {
  },
  methods: {
    show() {
      this.formData.id = ''
      this.formData.title = ''
      if (this.hotTableObj) {
        this.hotTableObj.loadData([])
      }
      this.doEdit = false
      this.openModal = true
    },
    // 表格初始化
    initTable() {
      if (!this.hotTableObj) {
        const container = this.$refs.hotTable
        this.hotTableObj = new Handsontable(container, this.hotSettings)
        this.hotTableObj.loadData([])
      }
      if (this.doEdit) {
        this.hotTableObj.loadData(this.formData.specs)
      }
    },

    // 预览
    previewClick() {
      if (this.newWeights !== null) {
        if (this.newWeightsCopy[0] !== 0) {
          this.newWeightsCopy.unshift(0)
        }
        const _ = require('underscore')
        // isEqual方法，判断两个变量是否相同,值是true或者false
        const bol = _.isEqual(JSON.stringify(this.newWeightsCopy), this.newWeightsOld)
        if (bol) {
          this.$Message.warning('输入框内的数据暂无发生变化')
          return
        }
        //  用于第三列和第四列数据生成
        this.newWeightsArr = this.newWeights.map(Number)
        this.newWeightsCopy = this.newWeightsCopy.map(Number)

        // 第一列的数据为字符串转  数字   二次map  转数组中包含数组
        this.newWeights = this.newWeights.map(Number).map((item) => {
          return [item]
        })
        // // 往数组中的 数组添加第二个数据   第五个数据
        var i = 0
        while (i < this.newWeights.length) {
          this.newWeights[i][1] = '固定费用'
          this.newWeights[i][4] = 1
          i++
        }
        // // 数组中的第一行  第三列数据 为0
        if (this.newWeightsArr[0] !== 0) {
          this.newWeightsArr.unshift(0)
        }
        this.newWeightsOld = JSON.stringify(this.newWeightsArr)
        var v = 0
        while (v < this.newWeights.length) {
          [this.newWeights[v][2], this.newWeights[v][3]] = [this.newWeightsArr[v], this.newWeightsArr[v + 1]]
          v++
        }
        const data = []
        // 转换为对象包数组   赋值里面的数据
        for (var k = 0; k < this.newWeights.length; k++) {
          this.newWeightsObj[k] = this.newWeights[k]
          data[k] = {
            title: this.newWeightsArr[k + 1],
            chargeType: '固定费用',
            fromWeight: this.newWeightsObj[k][2],
            toWeight: this.newWeightsObj[k][3],
            unitWeight: 1
          }
        }
        this.hotTableObj.loadData(data)
      } else {
        this.$Message.warning('检测到暂无数字,无法生成表格')
      }
    },
    submit() {
      const data = this.hotTableObj.getSourceData()
      this.formData.specs = data.splice(0, data.length - 1)
      if (!this.formData.specs[this.formData.specs.length - 1].title) {
        this.formData.specs[this.formData.specs.length - 1].title = '...'
      }
      this.formData.weightTxt = ''
      request({
        url: 'weight/add',
        data: this.formData,
        method: 'post'
      }).then(res => {
        if (res.success) {
          this.openModal = false
          this.$emit('query')
        }
      })
    },
    edit(data) {
      copyProperty(this.formData, data)
      // this.hotTableObj.loadData(data.specs)
      this.doEdit = true
      this.openModal = true
    }
  }
}
</script>
